<template>
  <div class="api-debug">
    <div class="debug-container">
      <el-card class="debug-card">
        <template #header>
          <div class="card-header">
            <span>API调试工具</span>
            <el-tag type="warning">实时调试</el-tag>
          </div>
        </template>

        <div class="debug-content">
          <!-- 发送验证码测试 -->
          <div class="api-section">
            <h3>🔧 发送验证码API测试</h3>
            <div class="api-form">
              <el-form :model="codeForm" label-width="100px">
                <el-form-item label="邮箱地址">
                  <el-input
                    v-model="codeForm.email"
                    placeholder="请输入QQ邮箱"
                    style="width: 300px;"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="testSendCode" :loading="sendingCode">
                    发送验证码
                  </el-button>
                  <el-button @click="fillTestEmail">填充测试邮箱</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="api-info">
              <p><strong>API地址:</strong> POST /user/send-code</p>
              <p><strong>请求参数:</strong> { "email": "string" }</p>
            </div>
            
            <div v-if="codeResponse" class="response-section">
              <h4>响应结果:</h4>
              <div class="response-display">
                <el-tag :type="codeResponse.success ? 'success' : 'danger'">
                  {{ codeResponse.success ? '成功' : '失败' }}
                </el-tag>
                <pre class="json-display">{{ JSON.stringify(codeResponse.data, null, 2) }}</pre>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 用户注册测试 -->
          <div class="api-section">
            <h3>📝 用户注册API测试</h3>
            <div class="api-form">
              <el-form :model="registerForm" label-width="100px">
                <el-form-item label="用户名">
                  <el-input v-model="registerForm.username" placeholder="用户名" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="registerForm.email" placeholder="邮箱" />
                </el-form-item>
                <el-form-item label="密码">
                  <el-input v-model="registerForm.password" placeholder="密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码">
                  <el-input v-model="registerForm.confirmPassword" placeholder="确认密码" show-password />
                </el-form-item>
                <el-form-item label="验证码">
                  <el-input v-model="registerForm.verificationCode" placeholder="验证码" />
                </el-form-item>
                <el-form-item>
                  <el-button type="success" @click="testRegister" :loading="registering">
                    测试注册
                  </el-button>
                  <el-button @click="fillTestRegister">填充测试数据</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div class="api-info">
              <p><strong>API地址:</strong> POST /user/register</p>
              <p><strong>请求参数:</strong></p>
              <pre class="api-params">{
  "username": "string",
  "email": "string",
  "password": "string", 
  "confirmPassword": "string",
  "verificationCode": "string"
}</pre>
            </div>
            
            <div v-if="registerResponse" class="response-section">
              <h4>响应结果:</h4>
              <div class="response-display">
                <el-tag :type="registerResponse.success ? 'success' : 'danger'">
                  {{ registerResponse.success ? '成功' : '失败' }}
                </el-tag>
                <pre class="json-display">{{ JSON.stringify(registerResponse.data, null, 2) }}</pre>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 网络状态检查 -->
          <div class="api-section">
            <h3>🌐 网络状态检查</h3>
            <div class="status-grid">
              <div class="status-item">
                <span class="status-label">前端服务:</span>
                <el-tag type="success">运行中 ({{ window.location.origin }})</el-tag>
              </div>
              <div class="status-item">
                <span class="status-label">后端连接:</span>
                <el-tag :type="backendStatus.type">{{ backendStatus.text }}</el-tag>
                <el-button size="small" @click="checkBackend" :loading="checkingBackend">
                  检查
                </el-button>
              </div>
              <div class="status-item">
                <span class="status-label">API Base URL:</span>
                <code>{{ apiBaseUrl }}</code>
              </div>
              <div class="status-item">
                <span class="status-label">完整API地址:</span>
                <code>{{ apiBaseUrl }}/user/send-code</code>
              </div>
              <div class="status-item">
                <span class="status-label">开发模式:</span>
                <el-tag :type="import.meta.env.DEV ? 'success' : 'warning'">
                  {{ import.meta.env.DEV ? '开发环境' : '生产环境' }}
                </el-tag>
              </div>
              <div class="status-item">
                <span class="status-label">代理状态:</span>
                <el-tag type="info">
                  {{ import.meta.env.DEV ? '使用代理' : '直连后端' }}
                </el-tag>
              </div>
            </div>
          </div>

          <!-- 请求日志 -->
          <div class="logs-section">
            <h3>📋 请求日志</h3>
            <div class="logs-container">
              <div v-if="requestLogs.length === 0" class="no-logs">
                暂无请求日志
              </div>
              <div v-for="(log, index) in requestLogs" :key="index" class="log-item">
                <div class="log-header">
                  <span class="log-time">{{ log.time }}</span>
                  <el-tag :type="log.success ? 'success' : 'danger'" size="small">
                    {{ log.method }} {{ log.url }}
                  </el-tag>
                </div>
                <div class="log-content">
                  <div class="log-request">
                    <strong>请求:</strong>
                    <pre>{{ JSON.stringify(log.request, null, 2) }}</pre>
                  </div>
                  <div class="log-response">
                    <strong>响应:</strong>
                    <pre>{{ JSON.stringify(log.response, null, 2) }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { sendRegisterCode, userRegister } from '@/utils/apiService'

// 响应式数据
const sendingCode = ref(false)
const registering = ref(false)
const checkingBackend = ref(false)
const codeResponse = ref(null)
const registerResponse = ref(null)
const requestLogs = ref([])

const backendStatus = reactive({
  type: 'info',
  text: '未检查'
})

const codeForm = reactive({
  email: ''
})

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: ''
})

// 计算属性
const apiBaseUrl = computed(() => {
  return import.meta.env.DEV ? '/housingHub' : 'http://localhost:8085/housingHub'
})

// 方法
const addLog = (method, url, request, response, success) => {
  requestLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    method,
    url,
    request,
    response,
    success
  })
  
  // 只保留最近10条日志
  if (requestLogs.value.length > 10) {
    requestLogs.value = requestLogs.value.slice(0, 10)
  }
}

const testSendCode = async () => {
  if (!codeForm.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }

  sendingCode.value = true
  codeResponse.value = null

  try {
    console.log('发送验证码请求:', { email: codeForm.email })
    
    const response = await sendRegisterCode(codeForm.email)

    console.log('🔍 验证码发送响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    codeResponse.value = {
      success: responseData.code === 200 || responseData.code === '200',
      data: responseData
    }

    addLog('POST', '/user/send-code', { email: codeForm.email }, responseData, responseData.code === 200 || responseData.code === '200')

    if (responseData.code === 200 || responseData.code === '200') {
      ElMessage.success('验证码发送成功')
    } else {
      ElMessage.error(responseData.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    const errorResponse = {
      error: error.message,
      status: error.response?.status,
      data: error.response?.data
    }
    
    codeResponse.value = {
      success: false,
      data: errorResponse
    }
    
    addLog('POST', '/user/send-code', { email: codeForm.email }, errorResponse, false)
    ElMessage.error('验证码发送失败: ' + error.message)
  } finally {
    sendingCode.value = false
  }
}

const testRegister = async () => {
  if (!registerForm.username || !registerForm.email || !registerForm.password || 
      !registerForm.confirmPassword || !registerForm.verificationCode) {
    ElMessage.warning('请填写完整的注册信息')
    return
  }

  registering.value = true
  registerResponse.value = null

  try {
    const requestData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      confirmPassword: registerForm.confirmPassword,
      verificationCode: registerForm.verificationCode
    }
    
    console.log('注册请求:', requestData)
    
    const response = await userRegister(requestData)
    
    registerResponse.value = {
      success: response.code === '200',
      data: response
    }
    
    addLog('POST', '/user/register', requestData, response, response.code === '200')
    
    if (response.code === '200') {
      ElMessage.success('注册成功')
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败:', error)
    const errorResponse = {
      error: error.message,
      status: error.response?.status,
      data: error.response?.data
    }
    
    registerResponse.value = {
      success: false,
      data: errorResponse
    }
    
    addLog('POST', '/user/register', registerForm, errorResponse, false)
    ElMessage.error('注册失败: ' + error.message)
  } finally {
    registering.value = false
  }
}

const fillTestEmail = () => {
  const timestamp = Date.now().toString().slice(-6)
  codeForm.email = `${timestamp}@qq.com`
  ElMessage.success('测试邮箱已填充')
}

const fillTestRegister = () => {
  const timestamp = Date.now().toString().slice(-6)
  registerForm.username = `testuser${timestamp}`
  registerForm.email = codeForm.email || `${timestamp}@qq.com`
  registerForm.password = 'Test123!@#'
  registerForm.confirmPassword = 'Test123!@#'
  registerForm.verificationCode = '123456'
  
  ElMessage.success('测试数据已填充')
}

const checkBackend = async () => {
  checkingBackend.value = true

  try {
    // 尝试发送一个简单的请求来检查后端连接
    const response = await fetch(apiBaseUrl.value + '/user/send-code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email: 'test@qq.com' })
    })

    const responseData = await response.text()
    console.log('Backend check response:', response.status, responseData)

    if (response.ok || response.status === 400) {
      // 400可能是业务错误，但说明后端是连通的
      backendStatus.type = 'success'
      backendStatus.text = '连接正常'
    } else {
      backendStatus.type = 'warning'
      backendStatus.text = `连接异常 (${response.status})`
    }

    addLog('POST', '/user/send-code', { email: 'test@qq.com' }, {
      status: response.status,
      data: responseData
    }, response.ok)

  } catch (error) {
    console.error('Backend check error:', error)
    backendStatus.type = 'danger'
    backendStatus.text = '连接失败: ' + error.message

    addLog('POST', '/user/send-code', { email: 'test@qq.com' }, {
      error: error.message
    }, false)
  } finally {
    checkingBackend.value = false
  }
}
</script>

<style scoped>
.api-debug {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.debug-container {
  max-width: 1000px;
  margin: 0 auto;
}

.debug-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.debug-content {
  padding: 20px 0;
}

.api-section {
  margin-bottom: 30px;
}

.api-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.api-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.api-info {
  background: #e6f7ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.api-info p {
  margin: 5px 0;
  color: #2c3e50;
}

.api-params {
  background: #2c3e50;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 5px;
}

.response-section h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.response-display {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.json-display {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 6px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  margin-top: 10px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-label {
  font-weight: 500;
  color: #2c3e50;
}

.logs-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
}

.no-logs {
  text-align: center;
  color: #909399;
  padding: 40px;
  background: #f8f9fa;
  border-radius: 8px;
}

.log-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.log-time {
  font-size: 12px;
  color: #909399;
}

.log-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.log-request, .log-response {
  background: #fff;
  padding: 10px;
  border-radius: 6px;
}

.log-request strong, .log-response strong {
  color: #2c3e50;
  display: block;
  margin-bottom: 5px;
}

.log-request pre, .log-response pre {
  background: #2c3e50;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  font-size: 11px;
  max-height: 150px;
  overflow-y: auto;
  white-space: pre-wrap;
}

code {
  background: #f1f2f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  color: #e74c3c;
}
</style>
